package com.ssyc.student.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ssyc.common.base.LazyBaseFragment;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.view.MyListView;
import com.ssyc.student.R;
import com.ssyc.student.activity.StudentReadActivity;
import com.ssyc.student.activity.StudentShowReadAnswerActivity;
import com.ssyc.student.adapter.StAnswerLvAdapter;
import com.ssyc.student.bean.ReadInfo;
import com.ssyc.student.bean.StAnswerInfo;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * 学生端--阅读
 * Created by Administrator on 2018/5/10 0010.
 */

public class StudentReadChooseAnswerFragment extends LazyBaseFragment {

    //阅读的题目内容
    private TextView tvTopic;

    //展示答案选项的ListView
    private MyListView lvAnswer;

    //展示正确答案选项
    private TextView tvCorrectAnswer;

    //展示正确的完整句子
    private TextView tvShowContent;

    //选择正确答案后需要展示的整体布局,默认不显示
    private LinearLayout llShowAnswer;


    //提供选择答案的数据集合
    private List<StAnswerInfo> answerInfos;

    //展示答案选项的列表适配器
    private StAnswerLvAdapter adapter;

    //当前题目的位置
    private int currPos;


    //通知Acitvity进行ViewPager翻页的标识
    public static String VPSCOLL = "StudentReadActivityVpScoll";


    //当前题目的正确答案,通过传值获取
    public String correctAnswer = "rightAnswer";

    //当前页面的问题对象
    private ReadInfo.DataBean.QuestionListBean.DetailListBean info;

    //字母数组
    private String[] letters;

    //下划线,替换服务器返回的填空二字
    private static final String RESSTRE = "_____";
    private List<ReadInfo.DataBean.QuestionListBean.DetailListBean.ReadOptionBean> optionBeans;

    /**
     * 提供的生成当前Fragment的方法
     *
     * @param data 包含页面数据的json字符串
     * @return
     */
    public static StudentReadChooseAnswerFragment newInstance(ReadInfo.DataBean.QuestionListBean.DetailListBean data, int pos) {

        StudentReadChooseAnswerFragment studentReadChooseAnswerFragment = new StudentReadChooseAnswerFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("data", data);
        bundle.putInt("pos", pos);
        studentReadChooseAnswerFragment.setArguments(bundle);

        return studentReadChooseAnswerFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_student_read_choose_answer;
    }

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {

    }

    @Override
    protected void init(View view, Bundle savedInstanceState) {
        super.init(view, savedInstanceState);
        showContent();

        //初始化视图
        initView(view);

        //获取传递的数据
        initData();

        //设置问题
        initQuestion();

        //设置正确答案
        initRightQuestion();

        //设置展示答案的ListView
        initLv();
    }


    /**
     * 设置显示的问题,使用下划线替代服务器返回的问题中的"填空"二字
     */
    private void initQuestion() {
        String quesiton = info.getRead_topic();
        tvTopic.setText(quesiton.replace("填空", RESSTRE));
    }

    /**
     * 初始化视图
     *
     * @param view
     */
    public void initView(View view) {
        tvTopic = view.findViewById(R.id.tv_topic);
        lvAnswer = view.findViewById(R.id.lv_answer);
        lvAnswer.setFocusable(false);
        tvCorrectAnswer = view.findViewById(R.id.tv_correct_answer);
        tvShowContent = view.findViewById(R.id.tv_show_content);
        llShowAnswer = view.findViewById(R.id.ll_show_answer);
        //默认是不显示的
        llShowAnswer.setVisibility(View.GONE);
        //获取字母的数组
        letters = getResources().getStringArray(R.array.base_letters);
    }

    /**
     * 模拟的答案选项
     */
    private void initData() {

        //获取当前页面的位置
        currPos = getArguments().getInt("pos");

        //获取当前页面对象
        info = (ReadInfo.DataBean.QuestionListBean.DetailListBean) getArguments().getSerializable("data");

        //获取正确答案
        correctAnswer = info.getRead_answer();
        Log.i("test", "info是:" + GsonUtil.objectToJson(info));

        //解析该Json获取页面数据
        answerInfos = new ArrayList<>();

        //获取服务器返回的当前问题的所有答案选项
        optionBeans = info.getRead_option();
        if (null != optionBeans && optionBeans.size() != 0) {
            for (int i = 0; i < optionBeans.size(); i++) {
                StAnswerInfo info = new StAnswerInfo();
                info.isSelect = false;
                info.answerContent = optionBeans.get(i).getOption_read();
                info.answerFlag = letters[i];
                answerInfos.add(info);
            }
        }
    }

    /**
     * 设置展示选择答案的ListView
     */
    private void initLv() {
        adapter = new StAnswerLvAdapter(getContext(), answerInfos, R.layout.student_lv_answer);
        lvAnswer.setAdapter(adapter);
        lvAnswer.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
                //条目的点击事件
                for (int i = 0; i < answerInfos.size(); i++) {
                    if (pos == i) {
                        answerInfos.get(pos).isSelect = true;
                    } else {
                        answerInfos.get(i).isSelect = false;
                    }
                }
                adapter.notifyDataSetChanged();

                //防止快速点击,只能单选,选择以后设置为不可继续交互
//                lvAnswer.setEnabled(false);

                //重新做题后需要通知提交界面的适配器数据刷新
                EventBus.getDefault().post(new BusInfo(StudentReadCommitFragment.HASDONE, currPos, answerInfos.get(pos).answerFlag));

                //将选择的答案保存到Acitivity的Map中
                StudentReadActivity.getChooseAnswerMap().put(currPos, answerInfos.get(pos).answerFlag);

                //判断选择答案的对错,然后保存到Map中
                if (answerInfos.get(pos).getAnswerContent().equals(correctAnswer)) {
                    //选择正确
                    StudentReadActivity.getAnswerMap().put(currPos, true);
                } else {
                    //选择错误
                    StudentReadActivity.getAnswerMap().put(currPos, false);
                }

                //选择答案后跳转到下一页面,EventBus通知Activity进行ViewPager的翻页操作
//                EventBus.getDefault().post(new BusInfo(VPSCOLL));
            }
        });
    }

    /**
     * 设置正确答案
     */
    private void initRightQuestion() {
        //计算正确答案的索引值
        tvCorrectAnswer.setText(letters[getRightIndex()]);
        //设置答案详解
        tvShowContent.setText(info.getRead_exp());
    }

    /**
     * 获取正确答案在服务器返回的所有选项中的位置
     */
    private int getRightIndex() {
        int index = -1;
        if (optionBeans != null && optionBeans.size() != 0) {
            for (int i = 0; i < optionBeans.size(); i++) {
//                if (info.getRead_answer().replaceAll(" ", "").equals(optionBeans.get(i).getOption_read().replaceAll(" ", ""))) {
                if (correctAnswer.replaceAll(" ", "").equals(optionBeans.get(i).getOption_read().replaceAll(" ", ""))) {
                    index = i;
                    break;
                }
            }
        }

        return index;
    }

    /**
     * 事件处理
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (null != busInfo && StudentShowReadAnswerActivity.LOOKANSWER == busInfo.getType()) {
            //显示答案布局
            llShowAnswer.setVisibility(View.VISIBLE);
            lvAnswer.setEnabled(false);
        }
    }
}
